package com.tcpudp.config;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class AuthInterceptor implements HandlerInterceptor {
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 允许登录请求通过
        if (request.getRequestURI().startsWith("/api/auth/login")) {
            return true;
        }
        
        // 允许静态资源访问
        if (request.getRequestURI().startsWith("/css/") || 
            request.getRequestURI().startsWith("/js/") || 
            request.getRequestURI().equals("/") || 
            request.getRequestURI().equals("/index.html")) {
            return true;
        }
        
        // 检查用户是否已登录
        HttpSession session = request.getSession(false);
        if (session != null && session.getAttribute("user") != null) {
            return true;
        }
        
        // 如果是API请求，返回401状态码
        if (request.getRequestURI().startsWith("/api/")) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json");
            response.getWriter().write("{\"error\":\"未授权访问\"}");
            return false;
        }
        
        // 否则重定向到登录页面
        response.sendRedirect("/login.html");
        return false;
    }
}